package com.xn.app.muying.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioGroup;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.ToastUtil;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 宝宝添加页面
 * Created by Administrator on 2016/11/9.
 */
public class BabyActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    //添加按钮
    private Button baby_birthday=null;
    //记录宝宝性别
    private int mGender=0;
    //数据库
    private DBManager db = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.activity_baby);
        //得到数据库对象
        db = new DBManager(this);
        //得到控件对象
        baby_birthday = (Button) findViewById(R.id.activity_baby_birthday);
        RadioGroup baby_rg = (RadioGroup) findViewById(R.id.activity_baby_rg);
        Button baby_submit = (Button) findViewById(R.id.activity_baby_submit);
        //添加返回键点击事件
        findViewById(R.id.activity_doctor_list_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //设置点击事件
        baby_rg.setOnCheckedChangeListener(this);
        baby_birthday.setOnClickListener(this);
        baby_submit.setOnClickListener(this);
    }

    /**
     * 性别选择功能
     * @param radioGroup  控件
     * @param checkedId   性别参数
     */
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.activity_baby_rb1:
                mGender = 1;
                break;
            case R.id.activity_baby_rb2:
                mGender = 2;
                break;
        }
    }

    /**
     * 点击事件
     * @param view  控件
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_baby_birthday:
                Calendar instance = Calendar.getInstance();
                DatePickerDialog pickerDialog = new DatePickerDialog(BabyActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            private StringBuffer stringBuffer;

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {
                                stringBuffer = new StringBuffer("");
                                stringBuffer.append(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " ");
                                baby_birthday.setText("" + stringBuffer);
                            }
                        }, instance.get(Calendar.YEAR),
                        instance.get(Calendar.MONTH),
                        instance.get(Calendar.DAY_OF_MONTH));
                pickerDialog.setTitle("日期");
                pickerDialog.setMessage("请选择预约时间");
                pickerDialog.setCancelable(false);
                pickerDialog.show();
                break;
            //提交宝宝信息
            case R.id.activity_baby_submit:
                String birthday = baby_birthday.getText().toString();
                if (birthday != null && !birthday.equals("") && !birthday.equals("null")) {
                    //如果宝宝生日小于等于今天就提交
                    if (DateUtils.getStringToDate2(birthday) <= DateUtils.getStringToDate2(DateUtils.getCurrentDate())) {
                        submit(mGender, baby_birthday.getText().toString());
                    } else {
                        ToastUtil.showToast(this, "宝宝还没有出生哦");
                    }
                } else {
                    ToastUtil.showToast(this, "请您仔细查看宝宝生日是否设置正确哦");
                }
                break;
        }
    }

    /**
     * 提交baby 信息
     *
     * @param mGender  baby性别
     * @param barthday baby生日
     */
    private void submit(final int mGender, final String barthday) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    HashMap<String, Object> param = new HashMap<>();
                    param.put("babyBirthday", barthday);
                    param.put("babyGender", mGender);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.BabyInfo).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        handler1.sendMessage(msg2);
                    }else{
                        Message msg2 = new Message();
                        msg2.what = 1;
                        msg2.obj=bodys;
                        handler1.sendMessage(msg2);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 得到线程返回的数据，更新UI组建
     */
    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    sendBroadcast(new Intent("bei_er").putExtra("bei_er", 0));
                    ToastUtil.showToast(BabyActivity.this, "宝宝信息添加成功");
                    break;
                case 1:
                    break;
            }
            finish();
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }
}
